// pages/canvasSign/index.js
import urls from '../../requestUrl.js'

const {
    $Toast
} = require('../../components/base/index');

var content = null;
var touchs = [];

var canvasw = 0;
var canvash = 0;





Page({

    /**
     * 页面的初始数据
     */
    data: {
        signatureImg: '',
        canvasWidth: canvasw,
        canvasHeight: canvash,
        isHiddenCanvas: true,
        uploadUrl: urls.baseUrl + urls.uploadUrl.signImg,
        isLock: false
    },
    /**初始化画布 */
    initCanvas: function() {
        //获得Canvas的上下文
        content = wx.createCanvasContext('signatureLayout')

        // this.drawBgImg()
        //设置线的颜色
        content.setStrokeStyle("#666666")
            //设置线的宽度
        content.setLineWidth(3)
            //设置线两端端点样式更加圆润
        content.setLineCap('round')
            //设置两条线连接处更加圆润
        content.setLineJoin('round')
    },
    /**画背景 */
    drawBgImg() {
        // content.drawImage('/assets/car.jpg', 0, 0, this.data.canvasWidth, this.data.canvasHeight)
        // content.draw()
        content.translate(this.data.canvasWidth / 2, this.data.canvasHeight / 2)
        content.strokeRect(0, 0, 150, 100)
        content.rotate(90 * Math.PI / 180)
        content.setStrokeStyle("red")
        content.strokeRect(0, 0, 150, 100)
            // content.rotate(20 * Math.PI / 180)
            // content.strokeRect(100, 10, 150, 100)
        content.draw()
    },
    /**
     * 触摸开始
     */
    handleTouchStar: function(e) {
        let point = {
            x: e.changedTouches[0].x,
            y: e.changedTouches[0].y
        }
        touchs.push(point)
    },

    /**
     * 触摸结束
     */
    handleTouchEnd: function(e) {
        console.log("触摸结束" + e)
            //清空轨迹数组
        for (let i = 0; i < touchs.length; i++) {
            touchs.pop()
        }
    },

    /**
     * 触摸移动
     */
    handleTouchMove: function(e) {
        let point = {
            x: e.touches[0].x,
            y: e.touches[0].y
        }
        touchs.push(point)
        if (touchs.length >= 2) {
            this.handleCanvasDraw(touchs)
        }

    },

    /**
     * 触摸取消
     */
    handleTouchCancel: function(e) {
        console.log("触摸取消", e)
    },

    /**/
    handleLongTap: function(e) {
        console.log("画布长按手势", e)
    },

    /**
     * 处理画布触摸异常
     */
    handleError: function(e) {
        console.log("画布触摸错误", e)
    },

    /**实现画图方法 */
    handleCanvasDraw: function() {
        let point1 = touchs[0]
        let point2 = touchs[1]
        touchs.shift()
        content.moveTo(point1.x, point1.y)
        content.lineTo(point2.x, point2.y)
        content.stroke()
        content.draw(true)
    },
    /**
     *清除画布
     * */
    clearCanvas: function(e) {
        content.clearRect(0, 0, this.data.canvasWidth + 2, this.data.canvasHeight + 2)
        content.draw(true)
    },
    /**
     *保存签名
     * */
    saveCanvas: function(e) {
        if (this.data.isLock) {
            return
        }
        this.data.isLock = true
        wx.canvasToTempFilePath({
            canvasId: 'signatureLayout',
            success: res => {
                console.log('签名临时地址', res.tempFilePath)
                this.setData({
                    signatureImg: res.tempFilePath
                })
                this.handleSignImg(res.tempFilePath);
            },
            complete: () => {
                this.data.isLock = false
            }
        }, this)
    },

    /**处理生成最后的签名图片 */
    handleSignImg(temPath) {
        this.setData({
            isHiddenCanvas: false
        })
        var cxt = wx.createCanvasContext('signatureLayout2')
        cxt.translate(this.data.canvasWidth / 2, (this.data.canvasHeight * 0.5) / 2)
        cxt.rotate(270 * Math.PI / 180)
        cxt.drawImage(temPath, (this.data.canvasWidth / 2) * -1, (this.data.canvasHeight * 0.5) / 2 * -1, this.data.canvasWidth, this.data.canvasHeight / 2)
        cxt.draw(false, () => {
            setTimeout(() => {
                console.log('draw next')
                wx.canvasToTempFilePath({
                    canvasId: 'signatureLayout2',
                    success: res => {
                        console.log('处理后的签名', res.tempFilePath)
                        this.uploadSignImg(res.tempFilePath)
                    },
                    fail: res => {
                        console.log('signatureLayout2 fail', res)
                    },
                    complete: () => {
                        this.setData({
                            isHiddenCanvas: true
                        })
                    }
                }, this)
            }, 500)
        })
    },

    /**上传签名图片 */
    uploadSignImg(filePath) {
        wx.showLoading({
            title: '签名上传中'
        })
        wx.uploadFile({
            url: this.data.uploadUrl,
            filePath: filePath,
            name: 'file',
            success: res => {
                var data = res.data
                console.log(data)
                let response = JSON.parse(data)
                this.saveGlobalToBack(response.data)
            },
            fail: res => {
                console.log('出错', index, res)
                wx.showModal({
                    content: '签名保存有误，请稍后重试',
                    showCancel: false,
                    success: res => {}
                })
            },
            complete: res => {
                wx.hideLoading()
            }
        })

    },

    /**保存全局并关闭签名页面 */
    saveGlobalToBack(path) {
        var signTemps = getApp().globalData.signTempPath
        signTemps[this.data.code] = path
        console.log(signTemps[this.data.code])
        console.log('signTemps', signTemps, signTemps[this.data.code])
        wx.showModal({
            content: '签名保存成功',
            showCancel: false,
            success: res => {
                if (res.confirm) wx.navigateBack()
            }
        })
    },

    /**
     * 取消签名
     */
    cancelCanvas: function() {
        wx.navigateBack()

    },
    /**展示签名 */
    showImage: function(e) {
        let urls = []
        urls.push(this.data.signatureImg)
        wx.previewImage({
            urls: urls
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {

        //获取系统信息
        wx.getSystemInfo({
                success: res => {
                    console.log('getSystemInfo', res)
                    canvasw = res.windowWidth - 15;
                    canvash = res.windowHeight - 60;
                    this.setData({
                        canvasWidth: canvasw,
                        canvasHeight: canvash,
                    })
                }
            })
            //
        this.initCanvas()
        let code = options.code
        this.setData({
            code: code,
            canvasWidth: canvasw,
            canvasHeight: canvash,
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        // $Toast({
        //   content: '使用内置的图标',
        //   icon: 'praise'
        // });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})